package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.serve.domain.*;
import com.zzyl.serve.dto.*;
import com.zzyl.serve.mapper.*;
import com.zzyl.serve.util.CodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.serve.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author MWJ
 * @date 2025-08-15
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        String idCardNo = dto.getCheckInElderDto().getIdCardNo();
        LambdaQueryWrapper<Elder> wrapper = Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, idCardNo);
        Elder selder = elderMapper.selectOne(wrapper);
        if(selder != null && selder.getStatus() != null ){
            throw new BaseException("该老人已入住");
        }
        //整理入住信息
        CheckInElderDto elderDto = dto.getCheckInElderDto();
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();

        Elder elder = new Elder();
        Contract contract = new Contract();
        CheckIn checkIn = new CheckIn();
        CheckInConfig checkInConfig = new CheckInConfig();

        BeanUtils.copyProperties(elderDto, elder);
        BeanUtils.copyProperties(checkInContractDto, contract);
        BeanUtils.copyProperties(checkInConfigDto, checkIn);
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);

        String elderFamilyJson= JSONUtil.toJsonStr(elderFamilyDtoList);
        //更新床位状态
        Bed bed = bedMapper.selectBedById(checkInConfigDto.getBedId());
        if(Objects.equals(bed.getBedStatus(),1)){
            throw new BaseException("该床位不为空");
        }
        bedMapper.setStatus1(checkInConfigDto.getBedId());
        //设置老人字段
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        if(selder != null && selder.getStatus() == null){
            elder.setId(selder.getId());
            elderMapper.updateById(elder);
        }else{
            elderMapper.insert(elder);
        }
        //设置checkin字段
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStatus(0);
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setRemark(elderFamilyJson);
        checkInMapper.insert(checkIn);
        //设置checkinConfig字段
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);

        //设置合同字段
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        //生成合同编号
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        LocalDateTime now = LocalDateTime.now();
        if(now.isBefore(checkInConfigDto.getStartDate())){
            contract.setStatus(0);
        }else if(now.isAfter(checkInConfigDto.getEndDate())){
            throw new BaseException("合同结束时间不能早于当前时间");
        }else{
            contract.setStatus(1);
        }
        contractMapper.insert(contract);
    }
}
